//
//  PriceViewController.m
//  SAT_NET
//
//  Created by lanou3g on 16/3/3.
//  Copyright © 2016年 郭丹. All rights reserved.
//

#import "PriceViewController.h"
#import "ProductPriceModel.h"
#import <UIImageView+WebCache.h>
#import "ProductCell.h"

@interface PriceViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, strong)NSMutableDictionary *dicAllData;
/// 点击左边的分类
@property(nonatomic, strong)NSString *sort;


@end
#warning 数据请求有差别，涉及到section的地方需要修改
@implementation PriceViewController

- (void)loadView {
    self.priceV = [[PriceView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.priceV;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setData];
    
    [self.priceV.leftTableV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"left_id"];
    [self.priceV.rightTableV registerClass:[ProductCell class] forCellReuseIdentifier:@"right_id"];
//    [self.priceV.rightTableV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"rightL_id"];
    
    self.priceV.rightTableV.delegate = self;
    self.priceV.rightTableV.dataSource = self;
    self.priceV.leftTableV.delegate = self;
    self.priceV.leftTableV.dataSource = self;
    
    
    [self setViews];
}

- (void)setData {
    [self setDataWithUrl:kPhoneListUrl];
    self.sort = @"手机";
    self.leftArray = [NSMutableArray arrayWithObjects:@"手机",@"笔记本电脑",@"平板电脑", nil];
    self.leftDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:kPhoneListUrl,@"手机",kNotebookListUrl,@"笔记本电脑", nil];
}

- (void)setViews {
    
    // 隐藏尾视图
    self.priceV.rightTableV.sectionFooterHeight = 0;
    
    // 首次进入选中：手机
    [self.priceV.leftTableV selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:(UITableViewScrollPositionNone)];
}

- (void)setDataWithUrl:(NSString *)url {
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            self.dicAllData = [NSMutableDictionary dictionary];
            NSDictionary *dicTem = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            for (NSString *key in dicTem.allKeys) {
                NSMutableArray *arrTem = [NSMutableArray array];
                if ([key isEqualToString:@"rank"] == YES) {
                    for (NSDictionary *dic in dicTem[key]) {
                        
                        ProductPriceModel *productPM = [[ProductPriceModel alloc] init];
                        [productPM setValuesForKeysWithDictionary:dic];
                        [arrTem addObject:productPM];
                    }
                    [self.dicAllData setValue:arrTem forKey:@"热门品牌"];
                    
                } else {
                    NSDictionary *dicABC = dicTem[key];
                    for (NSString *keyabc in [dicABC allKeys]) {
                        NSMutableArray *arr = [NSMutableArray array];
                        for (NSDictionary *dicNum in dicABC[keyabc]) {
                            ProductPriceModel *productPM = [[ProductPriceModel alloc] init];
                            [productPM setValuesForKeysWithDictionary:dicNum];
                            [arr addObject:productPM];
                        }
                        [self.dicAllData setValue:arr forKey:keyabc];
                    }
                }
                
            }
            // key值排序
            self.rightArray = self.dicAllData.allKeys.mutableCopy;
            [self.rightArray sortUsingSelector:@selector(compare:)];
            
            // 将"热门品牌"移到开始位置
            NSString *last = self.rightArray[self.rightArray.count - 1];
            [self.rightArray removeObject:last];
            [self.rightArray insertObject:last atIndex:0];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.priceV.rightTableV reloadData];
                NSLog(@"%ld",self.dicAllData.allKeys.count);
            });
        }
    }];
    [task resume];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.priceV.leftTableV == tableView) {
        return self.leftArray.count;
    } else {
        if (section < 2) {
            return 1;
        } else {
            return [self.dicAllData[self.rightArray[section - 2]] count];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView.tag == 101) {
        return 1;
    } else {
        return self.rightArray.count + 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 102) {
        
        if (indexPath.section < 2) {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rightL_id"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"rightL_id"];
            }
            // 显示小箭头
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            if (indexPath.section == 0) {
                cell.textLabel.text = @"排行榜";
            } else if (indexPath.section == 1) {
                cell.textLabel.text = [NSString stringWithFormat:@"全部%@",self.sort];
            }
            return cell;

        } else {
            ProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"right_id" forIndexPath:indexPath];
            NSArray *array = self.dicAllData[self.rightArray[indexPath.section - 2]];
            ProductPriceModel *productPM = array[indexPath.row];
            [cell.imageV sd_setImageWithURL:productPM.picUrl placeholderImage:[UIImage imageNamed:@"cancel"]];
            cell.label.text = productPM.name;
            return cell;
        }
        
        
        
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"left_id"];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.text = self.leftArray[indexPath.row];
        cell.backgroundColor = [UIColor colorWithRed:242.0 / 255 green:242.0 / 255 blue:242.0 / 255 alpha:1];
        
//        cell.contentView.backgroundColor = [UIColor clearColor];
        UIView *aView = [[UIView alloc] initWithFrame:cell.contentView.frame];
        aView.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = aView;   //设置选中后cell的背景颜色
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 101) {
        
        NSInteger index_row = indexPath.row;
        NSString *key = self.leftArray[index_row];
        NSString *url = self.leftDic[key];
        [self setDataWithUrl:url];

    } else {
        // goto the detailView
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.priceV.leftTableV) {
        return 0;
    }
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView == self.priceV.leftTableV) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 20)];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 7, 60, 16)];
    [view addSubview:lable];
    lable.font = [UIFont systemFontOfSize:14];
    lable.textColor = [UIColor grayColor];
    view.backgroundColor = [UIColor colorWithRed:242.0 / 255 green:242.0 / 255 blue:242.0 / 255 alpha:1];
    if (section == 0) {
        lable.text = @"排行榜";
    } else if (section == 1) {
        lable.text = @"筛选";
    } else {
        lable.text = self.rightArray[section - 2];
    }
    
    return view;
    
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    if (tableView == self.priceV.leftTableV) {
        return nil;
    }
    NSMutableArray *arrIndex = [NSMutableArray array];
    for (NSString *str in self.rightArray) {
//        NSMutableString *strIndex = str.mutableCopy;
//         [strIndex substringToIndex:1];
        NSString *strIndex = [str substringToIndex:1];
        [arrIndex addObject:strIndex];
    }
    [arrIndex insertObject:@"筛" atIndex:0];
    [arrIndex insertObject:@"排" atIndex:0];
    return arrIndex;
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
